package com.cv.system.service.user;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.cv.framework.common.exception.ErrorCode;
import com.cv.system.dal.dataobject.user.SystemUsersDO;
import com.cv.system.dal.mapper.user.SystemUserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.cv.framework.common.exception.utils.ServiceExceptionUtil.exception;
import static com.cv.system.ErrorCodeConstants.*;

/**
 * 用户信息校验业务层接口实现类
 *
 * @author Charles_XDXD
 */
@Service
public class UserInfoValidateServiceImpl implements UserInfoValidateService {

    @Resource
    private SystemUserMapper systemUserMapper;

    @Override
    public void validateUsernameUnique(Long userId, String username) {
        validateUnique(userId, username, SystemUsersDO::getUsername, VALIDATE_USERNAME_EXISTS);
    }

    @Override
    public void validateUserMobileUnique(Long userId, String mobile) {
        validateUnique(userId, mobile, SystemUsersDO::getMobile, VALIDATE_MOBILE_EXISTS);
    }

    @Override
    public void validateUserEmailUnique(Long userId, String email) {
        validateUnique(userId, email, SystemUsersDO::getEmail, VALIDATE_EMAIL_EXISTS);
    }

    private void validateUnique(Long userId, String value, SFunction<SystemUsersDO, String> fieldExtractor, ErrorCode errorCode) {
        if (StrUtil.isEmpty(value)) {
            return;
        }

        LambdaQueryWrapper<SystemUsersDO> queryWrapper = new LambdaQueryWrapper<SystemUsersDO>()
                .eq(fieldExtractor, value);

        if (ObjUtil.isNotEmpty(userId)) {
            queryWrapper.ne(SystemUsersDO::getId, userId);
        }

        if (ObjUtil.isNotEmpty(systemUserMapper.selectOne(queryWrapper))) {
            throw exception(errorCode);
        }
    }

}
